package com.yueban.activity;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.yueban.R;
import com.yueban.views.CircleSmartImageView;
import com.yueban.adapter.HomeActivitiesListAdapter;
import com.yueban.constant.HttpConstant;
import com.yueban.model.BaseResponse;
import com.yueban.model.DataHolder;
import com.yueban.model.User;
import com.yueban.net.NetWorkController;
import com.yueban.util.SPManager;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

public class PersonalPublishActivity extends AppCompatActivity {

    private SwipeRefreshLayout refreshLayout;
    private HomeActivitiesListAdapter adapter;
    private SPManager spManager;
    private NetWorkController netWorkController;
    private long userId;
    private TextView userName;
    private CircleSmartImageView imageView;
    private TextView userInfo;

    private final int LOAD_NEW = 0;
    private final int LOAD_MORE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_publish);

        userId = getIntent().getLongExtra("userId", -1);
        initView();
        netWorkController = new NetWorkController();
    }

    private void initView() {
        spManager = new SPManager(getApplicationContext());


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_release);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //设置私信按钮是否显示
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        if (userId != spManager.getUserId()) {
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
        } else {
            fab.setVisibility(View.GONE);
        }
        //显示姓名
        userName = (TextView) findViewById(R.id.personal_uname);

        //显示头像
        imageView = (CircleSmartImageView) findViewById(R.id.personalIcon);
        imageView.setImageUrl(HttpConstant.SERVER_URL + HttpConstant.GET_USER_ICON
                + "?userId=" + userId);
        //显示个人简介
        userInfo = (TextView) findViewById(R.id.personal_info);
        //userInfo.setText(user.getSex() + "," + user.getUniversity() + "," + user.getCollege() + "。");
        //注册swipRefreshLayout
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.srf_personal);
        //设置进度条（圈）颜色
        refreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));

        //下拉刷新动作
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getData(LOAD_NEW);
            }
        });
        //注册RecycleView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ryc_personal);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                //如果已显示到最后一条
                if (lastVisibleItemPosition + 1 == adapter.getItemCount()) {
                    if (refreshLayout.isRefreshing()) {
                        return;
                    } else {
                        //上拉加载
                        refreshLayout.setRefreshing(true);
                        getData(LOAD_MORE);
                    }
                }
            }
        });
        //适配器载入数据
        DataHolder dataHolder = new DataHolder();
        adapter = new HomeActivitiesListAdapter(dataHolder);
        //绑定适配器
        recyclerView.setAdapter(adapter);

        //自动刷新一次
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                //开启刷新进度条，将会在getData（）后关闭
                refreshLayout.setRefreshing(true);
                getData(LOAD_NEW);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        netWorkController.getUserInfo(userId).subscribe(new Observer<BaseResponse<User>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull BaseResponse<User> userBaseResponse) {
                if (userBaseResponse.getStatus() == 0) {
                    User user = userBaseResponse.getData();
                    userName.setText(user.getName());
                    userInfo.setText(user.getSex() + "," + user.getUniversity() + ","
                            + user.getCollege() + "。");
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Toast.makeText(PersonalPublishActivity.this,e.toString(),Toast.LENGTH_LONG).show();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    private void getData(int purpose) {

        adapter.notifyDataSetChanged();
        //关闭进度条
        refreshLayout.setRefreshing(false);
    }
}
